/* 13. 还书 */
"use strict";

const CHECK = require("../myUtil/formatCheck");
const { StrTime } = require("../myUtil/lib");
const DATEUTIL = require("../myUtil/DateUtil");
const db = require("../../coSqlite3");
const HTM = require("../myUtil/lib").html;

exports.returnBook = function* (req, res) {
    console.log("----------------------13. 还书\n");
    let rID = req.body.rID;
    let bID = req.body.bID;
    let htm = "";

    let htm1 = HTM.divBegin + 1 + HTM.divEnd;
    if (rID == "") {
      return HTM.begin + htm1 + "该证号不存在" + HTM.end;
    }

    let htm2 = HTM.divBegin + 2 + HTM.divEnd;
    if (bID == "") {
      return HTM.begin + htm2 + "该书号不存在" + HTM.end;
    }

    try {
        let rIDExist = yield db.execSQL("SELECT count(rid) as count FROM reader WHERE rid = ?", [rID]);
        if (rIDExist[0].count == 0) {
            return HTM.begin + htm1 + "该证号不存在" + HTM.end;
        }

        let bIDExist = yield db.execSQL("SELECT count(bid) as count FROM book WHERE bid = ?", [bID]);
        if (bIDExist[0].count == 0) {
            return HTM.begin + htm2 + "该书号不存在" + HTM.end;
        }

        let BookBorrowed = yield db.execSQL("SELECT count(bid) as count FROM process WHERE rid = ? and bid = ? and returned = 0", [rID, bID]);
        if (BookBorrowed[0].count == 0) {
            htm = HTM.divBegin + 3 + HTM.divEnd;
            return HTM.begin + htm + "该读者并未借阅该书" + HTM.end;
        }

        yield db.execSQL("UPDATE process SET returned = 1 WHERE rid = ? and bid = ?", [rID, bID]);
        // 库存+1
        yield db.execSQL('UPDATE book SET btruecnt = btruecnt + 1 WHERE bid = ?', [bID]);

    } catch (e) {
         htm = HTM.divBegin + 6 + HTM.divEnd + "数据库执行错误: " + e;
        return HTM.begin + htm + HTM.end;
    }

    htm = HTM.divBegin + 0 + HTM.divEnd;
    return HTM.begin + htm + '成功' + HTM.end;
}

